package com.lifeng.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by lifeng on 2018/5/9.
 */
@Component
public class MyIPZuulFilter extends ZuulFilter{
    private static final Logger log = LoggerFactory.getLogger(MyIPZuulFilter.class);
    /**过滤类型
     filterType：返回一个字符串代表过滤器的类型，在zuul中定义了四种不同生命周期的过滤器类型，具体如下：
         pre：路由之前
         routing：路由之时
         post： 路由之后
         error：发送错误调用
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**filterOrder：过滤的顺序
     * 请求在一个阶段中存在多个过滤器时，依次执行
     * pre :filterOrder 0 -> pre:filterOrder 1 -> routing: filterOrder 1
     * routing: filterOrder 2
     * 顺序: pre ->routing -> post ,*/
    @Override
    public int filterOrder() {
        log.info("MyIPFilter过滤器执行啦。。。");
        return 0;
    }
    /**这里可以写逻辑判断，是否要过滤，本文true,永远过滤
     *
     * 顺序: pre ->routing -> post ,以上3个顺序出现异常时都可以触发error类型的filter
     * */
    @Override
    public boolean shouldFilter() {
        return true;
    }
    /**过滤器的具体逻辑。可用很复杂，
     * 包括查sql，nosql去判断该请求到底有没有权限访问*/
    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest req =ctx.getRequest();
        String ip = getIpAddr(req);
        log.info("请求ip:"+ip);
        if(!"127.0.0.1".equals(ip)){
            log.info("IP地址校验不通过！！！");
            ctx.setResponseStatusCode(401);
            ctx.setSendZuulResponse(false);
            ctx.set("isOK",false);//可以把一些值放到ctx中，便于后面的filter获取使用
            ctx.setResponseBody("IpAddr is forbidden!");
            return null;
        }
        ctx.set("isOK",true);//可以把一些值放到ctx中，便于后面的filter获取使用
        log.info("IP校验通过。");
        return null;
    }

    /**
     * 获取Ip地址
     * @param request
     * @return
     */
    public  String getIpAddr(HttpServletRequest request){

        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
